package com.example.imtoken.modules.main.wallet.manage.wallet.imp.privates

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.example.imtoken.R
import com.example.imtoken.core.App
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.http.ApiException
import com.example.imtoken.core.http.BaseObserver
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.core.logic.repository.WalletRepository
import com.example.imtoken.core.utils.BusConfig
import com.example.imtoken.entitys.http.CoinsEntity
import com.example.imtoken.entitys.http.CreateEntityItem
import com.example.imtoken.entitys.http.ResponseEntity
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.AccountSchema
import com.example.imtoken.room.schema.WalletCheckedSchema
import io.reactivex.Observable
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch

class PrivateImportWalletViewModel(private val repository: WalletRepository) : BaseViewModel() {

    val private = MutableLiveData<String>()
    val pass1 = MutableLiveData<String>()
    val pass2 = MutableLiveData<String>()
    val passTips = MutableLiveData<String>()
    val isSubmit = MutableLiveData(false)
    val isSuccess = MutableLiveData(false)

    var createEntity: CreateEntityItem? = null

    var _private: String? = null
        set(value) {
            field = value
            inspectEditText()
        }

    var _pass1: String? = null
        set(value) {
            field = value
            inspectEditText()
        }

    var _pass2: String? = null
        set(value) {
            field = value
            inspectEditText()
        }

    private fun inspectEditText() {
        isSubmit.value =
            _private?.length ?: 0 > 0 && _pass1?.length ?: 0 > 0 && _pass2?.length ?: 0 > 0
    }

    fun verifyParams(): Boolean {
        return when {
            pass1.value != pass2.value -> {
                mErrorResId.value = R.string.createUserTips_pass
                false
            }
            else -> {
                true
            }
        }
    }

    fun impWallet2(coin: String?) {
        mDialog.value = true
        viewModelScope.launch {
            try {
                createEntity = repository.getWalletFind2(
                    coin,
                    private = private.value,
                    password = pass1.value,
                    hint = passTips.value
                )
                addAccountData()
                val coins = repository.getCoins(createEntity?.coin?.coin ?: "eth")

                App.appCode?.let { code ->
                    val bindingWallet = repository.bindingWallet(
                        createEntity?.coin?.address,
                        pass1.value,
                        coin ?: "eth",
                        code
                    )
                    bindingWallet?.let { LogUtils.json(it) }
                }
                mDialog.value = false
                addWalletChecked(coins)
            } catch (e: Exception) {
                mDialog.value = false
                mErrorStr.value = StringUtils.getString(R.string.impErrorTips)
            }
        }
    }

//    fun impWallet(coin: String?) {
//        mDialog.postValue(true)
//        RetrofitUtils.apiService?.walletFind(
//            coin,
//            private = private.value,
//            password = pass1.value,
//            hint = passTips.value
//        )
//            ?.flatMap(Function<ResponseEntity<CreateEntityItem>, Observable<ResponseEntity<CoinsEntity>>> {
//                if (it.code == 0) {
//                    createEntity = it.data
//                    if (addAccountData()) {
//                        return@Function RetrofitUtils.apiService?.coins(createEntity?.coin?.coin)
//                    } else {
//                        mDialog.postValue(false)
//                        return@Function Observable.error {
//                            ApiException(StringUtils.getString(R.string.impErrorTips))
//                        }
//                    }
//                } else {
//                    mDialog.postValue(false)
//                    return@Function Observable.error {
//                        ApiException(it.msg)
//                    }
//                }
//            })
//            ?.subscribeOn(Schedulers.io())
//            ?.unsubscribeOn(Schedulers.io())
//            ?.subscribe(object : BaseObserver<ResponseEntity<CoinsEntity>>() {
//                override fun onSuccess(value: ResponseEntity<CoinsEntity>) {
//                    mDialog.postValue(false)
//                    if (value.code == 0) {
//                        addWalletChecked(value.data)
//                    } else {
//                        mErrorStr.postValue(value.msg)
//                    }
//                }
//
//                override fun onFailed(e: Throwable) {
//                    mDialog.postValue(false)
//                }
//
//            })
//    }

    private fun addAccountData(): Boolean {
        val isCount =
            AppDataBase.instance.getAccountDao().findAccountExist(createEntity?.coin?.address)
        if (isCount > 0) {
            mErrorResId.postValue(R.string.impErrorTips)
            return false
        }
        val account = AccountSchema(
            null,
            pass1.value,
            passTips.value,
            createEntity?.token,
            createEntity?.coin?.address,
            createEntity?.coin?.coin,
            createEntity?.coin?.mnemonic,
            createEntity?.coin?.public_key,
            createEntity?.coin?.coin,
            4
        )
        return if (AppDataBase.instance.getAccountDao().insertAccount(account) > 0) {
            LogUtils.e("钱包账号添加成功")
            true
        } else {
            LogUtils.e("钱包账号添加失败")
            false
        }
    }

    fun addWalletChecked(coinsEntity: CoinsEntity?) {
        coinsEntity?.let {
            if (it.size > 0) {
                val item = it[0]
                val walletCheckedSchema = WalletCheckedSchema(
                    item.icon,
                    item.coin,
                    item.name,
                    createEntity?.coin?.address,
                    item.describe
                )
                if (AppDataBase.instance.getWalletCheckedDao()
                        .insertWalletChecked(walletCheckedSchema) > 0
                ) {
                    LogUtils.e("添加选择-${item.coin}-成功")
                    switchWallet(true)
                } else {
                    LogUtils.e("添加选择-${item.coin}-失败")
                    switchWallet(false)
                }
            }
        }
    }

    private fun switchWallet(b: Boolean) {
        //切换钱包到当前导入钱包
        val appLogin = AppDataBase.instance.getAppLoginDao().getAppLogin()
        appLogin.walletAddress = createEntity?.coin?.address
        if (AppDataBase.instance.getAppLoginDao().updateAppLogin(appLogin) > 0) {
            LogUtils.e("切换导入钱包成功")
            BusUtils.postSticky(BusConfig.update_default_account_sticky_wallet_fragment)
        }
        isSuccess.postValue(b)
    }

}